package com.zhuhjay.boot.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.boot.mapper.CheckGroupMapper;
import com.zhuhjay.domain.entity.CheckGroup;
import com.zhuhjay.domain.http.PageResult;
import com.zhuhjay.domain.http.QueryPageBean;
import com.zhuhjay.service.CheckGroupService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuhjay
 * @since 2022-04-02
 */
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl extends ServiceImpl<CheckGroupMapper, CheckGroup> implements CheckGroupService {

    @Override
    public void add(Integer[] ids, CheckGroup checkGroup) {
        // 新增检查组
        baseMapper.insert(checkGroup);
        // 检查组和检查项关联
        if( ids != null && ids.length != 0 ){
            for (Integer id : ids) {
                baseMapper.addRelationAndItemId(id, checkGroup.getId());
            }
        }
    }

    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        Page<CheckGroup> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        QueryWrapper<CheckGroup> queryWrapper = new QueryWrapper<>();
        if( queryString != null && queryString.trim().length() > 0 ){
            queryWrapper
                    .eq("code", queryString)
                    .or()
                    .eq("name", queryString);
        }
        IPage<CheckGroup> selectPage = baseMapper.selectPage(page, queryWrapper);
        return new PageResult(selectPage.getTotal(), selectPage.getRecords());
    }

    @Override
    public List<Integer> queryRelationByCheckGroupId(Integer id) {
        return baseMapper.queryCheckitemAndCheckgroupRelateion(id);
    }

    @Override
    public void edit(Integer[] ids, CheckGroup checkGroup) {
        baseMapper.updateById(checkGroup);
        // 删除所有关联数据
        baseMapper.clearCheckitemAndCheckgroupRelateion(checkGroup.getId());
        // 重新添加关联数据
        if( ids != null && ids.length != 0 ){
            for (Integer id : ids) {
                baseMapper.addRelationAndItemId(id, checkGroup.getId());
            }
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return baseMapper.selectList(null);
    }
}
